package com.dance.netty.netty.protobuf;

import com.dance.netty.netty.protobuf.pojo.StudentPOJO;
import com.dance.netty.netty.protobuf.proto.MyDataInfo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;
import java.util.Random;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送一个Student对象到服务器
//        StudentPOJO.Student dance = StudentPOJO.Student.newBuilder().setId(4).setName("dance").build();
//        ctx.writeAndFlush(dance);
        // 随机发送Student或者Worker
        int i = new Random().nextInt(3);
        MyDataInfo.MyMessage myMessage = null;
        if(0 == i){
            myMessage = MyDataInfo.MyMessage.newBuilder()
                    .setDataType(MyDataInfo.MyMessage.DataType.StudentType)
                    .setStudent(MyDataInfo.Student.newBuilder().setId(1).setName("flower").build()).build();
        }else{
            myMessage = MyDataInfo.MyMessage.newBuilder()
                    .setDataType(MyDataInfo.MyMessage.DataType.WorkerType)
                    .setWorker(MyDataInfo.Worker.newBuilder().setId(2).setName("dance").build()).build();
        }
        ctx.writeAndFlush(myMessage);
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("服务器回复的消息: " + byteBuf.toString(StandardCharsets.UTF_8));
        System.out.println("服务器地址: " + ctx.channel().remoteAddress());
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }
}
